
(function(){
  'use strict';
  function hasRealFavorites(){
    try{
      var raw = localStorage.getItem('rt_fav_tracks');
      var ids = raw ? JSON.parse(raw) : [];
      return Array.isArray(ids) && ids.length > 0;
    }catch(e){ return false; }
  }

  function sampleCards(){
    var items = [
      { id:'RTM-CT-001', title:'量子曙光-发布会开场', url:'track.html', cover:'', bpm:92, len:'02:18' },
      { id:'RTM-BR-010', title:'星链觉醒-品牌开篇', url:'track.html', cover:'', bpm:120, len:'02:32' },
      { id:'RTM-EP-023', title:'光锥加速-企业发布', url:'track.html', cover:'', bpm:96, len:'02:02' }
    ];
    var html = '<div data-demo="true">'
      + '<div class="card" style="margin-bottom:12px">'
      +   '<div class="row" style="align-items:center;gap:8px">'
      +     '<strong>示例演示</strong>'
      +     '<span class="muted" style="margin-left:8px">这是收藏后的展示效果。真正收藏后，这些示例会自动隐藏。</span>'
      +   '</div>'
      + '</div>'
      + '<div class="grid cards">'
      + items.map(function(m){
          return (
            '<div class="card">'
            +  '<div class="row" style="align-items:center;gap:12px">'
            +    '<div class="thumb" style="width:48px;height:48px;border-radius:6px;overflow:hidden;'
            +      'background:linear-gradient(135deg,#2b6fff,#0bd1e3);display:flex;align-items:center;justify-content:center;color:#fff">♪</div>'
            +    '<div class="col">'
            +      '<div class="title" style="font-weight:600">'+ m.title +'</div>'
            +      '<div class="muted" style="font-size:12px">ID: '+ m.id +' · '+ (m.bpm||'--') +' BPM · '+ (m.len||'--:--') +'</div>'
            +    '</div>'
            +    '<div class="col" style="flex:0 0 auto;display:flex;gap:8px">'
            +      '<a class="btn small" href="'+ m.url +'">进入</a>'
            +      '<button class="btn small" disabled>★ 已收藏</button>'
            +    '</div>'
            +  '</div>'
            +'</div>'
          );
        }).join('')
      + '</div>'
      + '</div>';
    return html;
  }

  function renderDemoIfEmpty(){
    try{
      var host = document.querySelector('#fav-list, .favorites-host, [data-favorites]');
      if(!host) return;
      // 如果已经有真实收藏则不覆盖；否则填充示例
      var empty = !host.children.length || !host.textContent.trim();
      if(!hasRealFavorites() && empty){
        host.innerHTML = sampleCards();
      }
    }catch(e){ /* no-op */ }
  }

  document.addEventListener('DOMContentLoaded', function(){
    // 等其它脚本（若有）运行后再渲染
    setTimeout(renderDemoIfEmpty, 0);
  });

  // 一旦产生真实收藏，移除示例
  document.addEventListener('rt:favorites:changed', function(){
    try{
      var host = document.querySelector('#fav-list, .favorites-host, [data-favorites]');
      if(!host) return;
      if(hasRealFavorites()){
        var demo = host.querySelector('[data-demo]');
        if(demo){ host.removeChild(demo); }
      }
    }catch(e){ /* no-op */ }
  });
})();
